import pyautogui as ag
import pygetwindow
import win32gui
import re
import requests
from Stock import Stock

STOCKCODE_RE = '[0-9]{6}'

class Moniter:
    """
    监视者，可以监控new预警，看出来是否有新的股票
    """

    def __init__(self):
        self.now_alerted_stock2 = None
        self.build_name_code_dict()
        print(self.name_code_dict)
        # self._build_main_windows()

    def check(self):
        if not self._build_main_windows():
            ag.alert(title='警告', text='找不到大智慧主窗口，请重新打开大智慧再尝试', button='我再试试看')
            return False
        else:
            print('**MainMoniter** ', 'main windows', self.main_win)
            return True

    def build_name_code_dict(self):
        # TODO: 对这个requests做错误处理和重试
        def by_jinshuyuan():
            response = requests.get('http://api.jinshuyuan.net/get_stk_dic')
            name_code_dict = {}
            datas = response.text
            datas = datas.split('<br/>')[1:]
            max_len = 0
            for data in datas:
                if data == '':
                    continue
                else:
                    data = data.split(',')
                    id_, code, name = data
                    max_len = len(name) if len(name) > max_len else max_len
                    name_code_dict[name] = code.lower()
            return name_code_dict
        def by_dongfang():
            response = requests.get('http://quote.eastmoney.com/stock_list.html')
            a = re.compile('html">(.*)\(([0-9]{6})\)</a></li>')
            datas = a.findall(response.text)
            name_code_dict = {}
            for name, code in datas:
                name = name.encode(response.encoding).decode('GBK')
                name_code_dict[name] = code
            return name_code_dict

        print('**Main Moniter** build name code dict')
        self.name_code_dict = by_jinshuyuan()
        self.name_code_dict.update(by_dongfang())
        print(self.name_code_dict)

    @property
    def main_new(self):
        """
        判断主窗口是否监控到了新数据
        :return: 是否是新数据(bool)，股票对象
        """
        stock_code, stock_name = self.get_code_by_main_window()
        if stock_code is None:
            return False, None
        else:
            self.now_alerted_stock2 = Stock(stock_code, stock_name)
            print(True, self.now_alerted_stock2)
            return True, self.now_alerted_stock2

    def _build_main_windows(self):
        wins = pygetwindow.getWindowsWithTitle('大智慧 - [')
        main_win = 0
        if len(wins) == 1:
            main_win = wins[0]._hWnd
        else:
            for win in wins:
                title = win32gui.GetWindowText(win)
                if title.startswith('大智慧 - [') and title.endswith(']'):
                    main_win = win._hWnd

        if main_win != 0:
            self.main_win = main_win
            return True
        else:
            return False

    def get_code_by_main_window(self):
        """
        通过检测主窗口的[]中的名字是否在字典中，来获得代码
        :return:
        """
        if not hasattr(self, 'main_win') or self.main_win == 0:
            raise Exception('Has not yet init main window')
        if not hasattr(self, 'name_code_dict'):
            raise Exception('Has not yet init name code dict')
        name = win32gui.GetWindowText(self.main_win)
        stock_name = name.replace('大智慧 - [', '').replace(']', '')
        stock_name = stock_name.replace(' ', '')
        print('**Main Moniter**', stock_name)
        # print(stock_name, self.name_code_dict.get(stock_name, None))
        return self.name_code_dict.get(stock_name, None), stock_name


if __name__ == '__main__':
    import time
    start = time.time()
    Moniter()
    end = time.time()
    print(end-start)